package cn.edu.sdjzu.xg.bysj.service;


import cn.edu.sdjzu.xg.bysj.dao.SchoolDao;
import cn.edu.sdjzu.xg.bysj.domain.School;
import test.BysjException;
import util.JdbcHelper;
import util.Pagination;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

public final class SchoolService {
	private static SchoolDao schoolDao= SchoolDao.getInstance();
	private static SchoolService schoolService=new SchoolService();


	public static SchoolService getInstance(){
		return schoolService;
	}

	public Collection<School> findAll(List conditionList,Pagination pagination) throws SQLException {
		Connection connection = JdbcHelper.getConn();
		Collection<School> schools = schoolDao.findAll(conditionList,pagination,connection) ;
		JdbcHelper.close(connection);
		return schools;
	}

	public School find(Integer id) throws SQLException {
		Connection connection = JdbcHelper.getConn();
		School school = schoolDao.find(id,connection);
		JdbcHelper.close(connection);
		return school;
	}

	public boolean update(School school) throws SQLException {
		Connection connection = JdbcHelper.getConn();
		Boolean updateSchool = schoolDao.update(school,connection);
		JdbcHelper.close(connection);
		return updateSchool;
	}

	public boolean add(School school) throws SQLException {
		Connection connection = JdbcHelper.getConn();
		Boolean added = schoolDao.add(school,connection);
		JdbcHelper.close(connection);
		return added ;
	}
	public boolean delete(Integer id) throws SQLException ,BysjException{
		Connection connection = JdbcHelper.getConn();
		int countDepartmentsOfSchool = DepartmentService.getInstance().countAll(SchoolService.getInstance().find(id));
		if(countDepartmentsOfSchool ==0){
			boolean deleted = schoolDao.delete(id,connection);
			return deleted;
		}else{
			throw new BysjException(SchoolService.getInstance().find(id).getDescription()+"仍有下级属 性,不能删除");
		}
	}

	public boolean delete(School school) throws SQLException, BysjException {
		Connection connection = JdbcHelper.getConn();
		int countDepartmentsOfSchool = DepartmentService.getInstance().countAll(school);
		if(countDepartmentsOfSchool ==0){
			boolean deleted =schoolDao.delete(school,connection);
			return deleted;
		}else{
			throw new BysjException(school.getDescription()+"仍有下级属性,不能删除");
		}
	}
}